package vis;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TextCheckPanel extends JPanel implements KeyListener {
	private static final long serialVersionUID = 2222794625345959840L;
	
	private JTextField openText;
	private JTextField keyText;
	
	private String lastOpen = "";
	private String correct;
	
	private TextChecker checker = null;
	
	public TextCheckPanel(TextChecker checker, String lab1, String lab2)
	{
		super();
		this.checker = checker;
		setLayout(new GridBagLayout());
		
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = 0; gbc.gridy = 0;
		add(new JLabel("  " + lab1 + "  "), gbc);
		
		openText = new JTextField();
		openText.setFont(new Font(Font.MONOSPACED, Font.BOLD, 16));
		openText.addKeyListener(this);
		openText.setPreferredSize(new Dimension(500, 30));
		
		gbc = new GridBagConstraints();
		gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 0.8;
		add(openText, gbc);
		
		gbc = new GridBagConstraints();
		gbc.gridx = 0; gbc.gridy = 1;
		add(new JLabel("  " + lab2 + "  "), gbc);
		
		keyText = new JTextField();
		keyText.setFont(new Font(Font.MONOSPACED, Font.BOLD, 16));
		keyText.addKeyListener(this);
		keyText.setPreferredSize(new Dimension(500, 30));
		
		gbc = new GridBagConstraints();
		gbc.gridx = 1; gbc.gridy = 1; gbc.weightx = 0.8;
		add(keyText, gbc);
	}

	@Override
	public void keyPressed(KeyEvent arg0) {}
	@Override
	public void keyTyped(KeyEvent arg0) {}
	
	private void updateKey()
	{
		lastOpen = openText.getText();
		if(checker != null)
			correct = checker.getCorrect(lastOpen);
		else
			correct = "";
	}
	
	private void check()
	{
		if(correct.equalsIgnoreCase(keyText.getText()))
		{
			keyText.setForeground(Color.GREEN);
		}
		else if(correct.toLowerCase().startsWith(keyText.getText().toLowerCase()))
		{
			keyText.setForeground(Color.BLUE);
		}
		else
		{
			keyText.setForeground(Color.RED);
		}
		keyText.repaint();
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		if(arg0.getSource() == openText)
		{
			if(!openText.getText().equals(lastOpen))
			{
				updateKey();
				check();
			}
		}
		else
		{
			check();
		}
	}
	
	public void setText(String text)
	{
		openText.setText(text);
		openText.setEditable(false);
		keyText.setText("");
		updateKey();
		check();
	}
	
	public void setEditable(boolean ed)
	{
		openText.setEditable(ed);
	}
	
}
